package com.test.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.test.model.Product;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

@Service
public class FreemarkerService {

	Configuration freemarkerConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

	public void showHtml() {
		try {
			freemarkerConfig.setDirectoryForTemplateLoading(
					new File("/Users/wangxh/Documents/workspace/CommonTest/src/main/webapp/WEB-INF/freemarker"));
			freemarkerConfig.setDefaultEncoding("UTF-8");
			freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
			Map<String, Object> root = new HashMap<String, Object>();
			root.put("user", "Big Joe");
			Product latest = new Product();
			latest.setUrl("products/greenmouse.html");
			latest.setName("green mouse");
			root.put("latestProduct", latest);

			Template temp = freemarkerConfig.getTemplate("ftlindex.ftl");

			Writer out = new OutputStreamWriter(new FileOutputStream("/Users/wangxh/Downloads/success.html"), "UTF-8");
			temp.process(root, out);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}

	}

}
